package com.ideal.blockchain.service.block;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ideal.blockchain.config.ChannelContext;
import com.ideal.blockchain.config.HyperledgerConfiguration;
import com.ideal.blockchain.model.Org;
import org.hyperledger.fabric.sdk.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: Jackie
 * @date: 2021/01/06 12:05
 */
@Service
public class OrgService {
    @Autowired
    private HyperledgerConfiguration hyperledgerConfiguration;

    @Autowired
    private ChannelService channelService;


    public JSONObject orgInfo(String name, String peerWithOrg, String channelName) throws Exception {
        HFClient client = HFClient.createNewInstance();
        hyperledgerConfiguration.checkConfig(client);
        Org sampleOrg = HyperledgerConfiguration.config.getSampleOrg(peerWithOrg);
        client.setUserContext(sampleOrg.getUser(name));
        channelService.reconstructChannel(peerWithOrg, channelName, client);
        Channel channel = ChannelContext.get();
        JSONObject jsonObject = new JSONObject();
        JSONArray peerArray=new JSONArray();
        JSONArray ordererArray=new JSONArray();
        for(Orderer orderer:channel.getOrderers()){
            ordererArray.add(orderer.getName());
        }
        for(Peer peer:channel.getPeers()){
            peerArray.add(peer.getName());
        }
        jsonObject.put("height",channel.queryBlockchainInfo().getHeight());
        jsonObject.put("orgs",ordererArray);
        jsonObject.put("peers",peerArray);
        return jsonObject;
    }
}
